package utils.query;

import org.apache.commons.lang.StringUtils;
import play.mvc.Http;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class OrderBy{ 
	public String by; 
	public OrderType orderType; 
	
	private static Pattern orderStringPattern = Pattern.compile("([+|-]{1})([a-zA-Z0-9_\\.]+)");
	private static Pattern sortStringPattern = Pattern.compile("sort\\(.*\\)");

	public static enum OrderType {
		asc,desc;
	};
	
	public OrderBy(String by,OrderType ascOrDesc) { 
		this.by = by; 
		this.orderType = ascOrDesc;
	}
	
	public static OrderBy ascOrder(String by) {
		return new OrderBy(by, OrderType.asc);
	}
	
	public static OrderBy descOrder(String by) {
		return new OrderBy(by, OrderType.desc);
	}

	private static OrderBy getCurrentOrderBy(){
		String by = Http.Request.current().params.get("sidx");
		String order =  Http.Request.current().params.get("order");
		if(StringUtils.isEmpty(by)) return null;

		if(StringUtils.isNotEmpty(by)) {
			by = "t."+by;
		}
		if(order.equals("desc")) {
			return OrderBy.descOrder(by);
		}else {
			return OrderBy.ascOrder(by);
		}
	}

	public static List<OrderBy> BuildFromString(String rawString) {
		List<OrderBy> orderList = new ArrayList<OrderBy>();

		OrderBy orderBy = getCurrentOrderBy();
		if(orderBy!=null)
			orderList.add(getCurrentOrderBy());
		return orderList;
	}
	
	public String toString() {
		return by + " " + orderType.name() + " ";
	}
}